package cn.birdbaby.plugins.sync.fieldsyncer.entitysyncer;

import cn.birdbaby.plugins.constants.Constants;
import cn.birdbaby.plugins.sync.fieldsyncer.AbstractFieldSyncer;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;

import java.util.Collection;
import java.util.List;

/**
 * @author llorando 20/8/24 6:11 pm
 */
public abstract class GenGroupSupport extends AbstractFieldSyncer {
    @Override
    public PsiClass findClass(PsiClass psiClass) {
        Collection<PsiAnnotation> annotations = PsiTreeUtil.findChildrenOfAnyType(psiClass, PsiAnnotation.class);
        for (PsiAnnotation annotation : annotations) {
            String name = annotation.getQualifiedName();
            if (name.endsWith(getSuffix())) {
                PsiAnnotationMemberValue attributeValue = annotation.findAttributeValue("pkgName");
                String pkgName = attributeValue.getText().replace("\"", "");
                String className = pkgName + "." + getPrefix() + psiClass.getName() + getSuffix();
                PsiClass result = JavaPsiFacade.getInstance(psiClass.getProject()).findClass(className, GlobalSearchScope.allScope(psiClass.getProject()));
                return result;
            }
        }
        return null;
    }

    @Override
    public void addPsiElement(PsiClass destination, List<PsiElement> psiElements) {
        PsiJavaToken rbrace = locateRBrace(destination);//最后一个，一定是右大括号
        for (PsiElement element : psiElements) {
            PsiField copy = (PsiField) element.copy();

            //feign的接口不需要方法体
            Collection<PsiAnnotation> annotations = PsiTreeUtil.findChildrenOfAnyType(copy, PsiAnnotation.class);
            for (PsiAnnotation psiAnnotation : annotations) {
                String name = psiAnnotation.getNameReferenceElement().getReferenceName();
                //如果是FieldDesc注解，就把里面的内容塞给Schema
                if (name.equals(Constants.AnnotationName.FIELD_DESC)) {
                    PsiAnnotationMemberValue attributeValue = psiAnnotation.findAttributeValue("name");
                    PsiAnnotation schema = copy.getModifierList().addAnnotation(Constants.AnnotationName.SCHEMA);
                    schema.setDeclaredAttributeValue("title", attributeValue);
                }
                //字段上面的注解一律干掉
                psiAnnotation.delete();
            }
            destination.addBefore(copy, rbrace);
        }
    }
}
